/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package daw.controlador;

import com.griaule.grfingerjava.MatchingContext;
import daw.bean.Usuario;
import daw.util.Util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Luis
 */
public class Login extends HttpServlet {
   
@PersistenceUnit
private EntityManagerFactory emf;


    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String accion;
        HttpSession session;
        try {
            accion = request.getParameter("accion");
            session = request.getSession();
            if(accion!=null && accion.equalsIgnoreCase("out")){
                cerrarSesion(session, request, response);
            }else{
                iniciarSesion(session, request, response);
            }
        }catch(Exception e){
            e.printStackTrace(response.getWriter());
        } finally { 
            out.close();
        }
    }

    protected void iniciarSesion(HttpSession session, HttpServletRequest request, HttpServletResponse response)throws Exception{
        Object urlLogin;
        Usuario usuario = null;
        EntityManager em;

        String operacion = request.getParameter("operacion");
        em = emf.createEntityManager();

        String error="";
        if(operacion.equals("loginPorUsuario")){
            try {
                usuario = (Usuario)em.createNamedQuery("Usuario.findByUserAndPassword").
                        setParameter("user", request.getParameter("usuario")).
                        setParameter("password", request.getParameter("contrasenia")).
                        getSingleResult();
                em.close();
            }catch(Exception ex){
				ex.printStackTrace(response.getWriter());
                usuario = null;
                error = "Usuario o contraseña son inconrrectos, vuelva a intentarlo.";
            }
        }else if(operacion.equals("loginPorHuella")){
            String templatestring = request.getParameter("huellatemplate");
            byte[] templatebytes = Util.getStringToTemplate(templatestring);

            List usuarios = em.createNamedQuery("Usuario.findAll").getResultList();
            MatchingContext contexto = (MatchingContext)getServletContext().getAttribute("contextoHuella");
            usuario = Usuario.identificar(templatebytes, usuarios, contexto);
            if(usuario==null)
                error = "Usuario o contraseña son inconrrectos, vuelva a intentarlo.";
        }

        if(usuario!=null){
            session.setAttribute("usuario", usuario);
            urlLogin = session.getAttribute("login_reenvio");
            if(urlLogin!=null){
                response.sendRedirect(urlLogin.toString());
            }else{
                response.sendRedirect(getServletContext().getContextPath()+"/");
            }
        }else{
            //response.sendRedirect(getServletContext().getContextPath()+"/login/login.jsp?error="+error);
            request.setAttribute("error", error);
            request.getRequestDispatcher("login/login.jsp").forward(request, response);
        }
    }

    protected void cerrarSesion(HttpSession session, HttpServletRequest request, HttpServletResponse response)throws IOException{
        session.invalidate();
        response.sendRedirect(getServletContext().getContextPath()+"/");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
